package c.x.jy.redislock;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;

public class AloneLock implements Lock {
	AtomicReference<Thread> onwer =new AtomicReference<>();
//	DemoCas<Thread> onwer =new DemoCas<>();
	private LinkedBlockingDeque<Thread> wartier =new LinkedBlockingDeque<>();
	@Override
	public void lock() {
 
		if(!tryLock()){
			wartier.offer(Thread.currentThread());
			for(;;){
				Thread head=wartier.peek();
				if(head == Thread.currentThread()){
					if(!tryLock()){
						LockSupport.park();
					}else{
						wartier.poll();
						return;
					}
				}else{
					LockSupport.park();
				}
			}
		}
	}

	@Override
	public void lockInterruptibly() throws InterruptedException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean tryLock() {
		 //尝试拿锁   ，   如果  cas 原子操作成功 返回TRUE   如果old值为空则把当前线程设置进去
		return onwer.compareAndSet(null, Thread.currentThread());
	}
	
	 
	

	@Override
	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		// TODO Auto-generated method stub
		return  false;
	}
	public boolean tryunLock() {
		 //尝试拿锁   ，   如果  cas 原子操作成功 返回TRUE   如果old值为空则把当前线程设置进去
		return onwer.compareAndSet( Thread.currentThread(),null);
	}

	@Override
	public void unlock() {
	   if(tryunLock()){
		   Thread head=wartier.peek();
		   if(head!=null){
			   LockSupport.unpark(head);
		   }
	   }
		
	}

	@Override
	public Condition newCondition() {
		// TODO Auto-generated method stub
		return null;
	}

}
